package com.hui.account.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

import com.google.gson.Gson;
import com.hui.account.R;
import com.hui.account.database.SQLManage;
import com.hui.account.dialog.FileDialog;
import com.hui.account.entity.FileEntity;
import com.hui.account.entity.RecordEntity;
import com.hui.account.entity.UserEntity;
import com.hui.account.utils.CommonUtils;
import com.hui.account.utils.FileUtils;
import com.hui.account.utils.TimeUtils;
import com.hui.account.utils.ToastUtils;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 备份与恢复
 */
public class BackUpActivity extends AppCompatActivity implements View.OnClickListener {

    Button backBtn;

    Context context;

    LinearLayout backupLayout, recoverLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getApplicationContext();
        setContentView(R.layout.activity_back_up);

        // 1、设置屏幕顶部字体颜色
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

        // 2、初始化页面
        initView();
    }

    /**
     * 初始化页面
     */
    private void initView() {
        backBtn = findViewById(R.id.setting_backup_back);
        backupLayout = findViewById(R.id.setting_backup_ll_1);
        recoverLayout = findViewById(R.id.setting_backup_ll_2);

        backupLayout.setOnClickListener(this);
        recoverLayout.setOnClickListener(this);
    }

    /**
     * 执行数据备份
     */
    private boolean backUpData() throws Exception {
        JSONObject object = new JSONObject();
        Gson gson = new Gson();

        // 1、分页查询全部客户
        List<UserEntity> users = getUsers();
        if (null != users && users.size() > 0) {
            object.put("users", gson.toJson(users));
        }

        // 2、分页查询全部欠款单
        List<RecordEntity> records = getRecords();
        if (null != records && records.size() > 0) {
            object.put("records", gson.toJson(records));
        }

        // 3、分页查询全部文件
        List<FileEntity> files = getFiles();
        if (null != files && files.size() > 0) {
            object.put("files", gson.toJson(files));
        }

        // 4、使用IO流，将数据写入文件，存到手机SD卡
        if (object.isNull("users") && object.isNull("records") && object.isNull("files"))
            return false;

        return FileUtils.writeTxtToFile(object.toString(), CommonUtils.BACKUP_PATH, "BACKUP-" + TimeUtils.getTodayTime() + ".txt");
    }

    /**
     * 执行数据恢复
     */
    private void recoverData() {
        FileDialog dialog = new FileDialog(this);
        dialog.show();
        dialog.setDialogSize();
    }

    /**
     * 分页查询数据
     */
    public List<UserEntity> getUsers() {
        int curPage = 0; // 起始页码
        int pageSize = 500; // 每页查询最大数
        List<UserEntity> list = new ArrayList<>();
        boolean flag = true;
        while (flag) {
            List<UserEntity> records = SQLManage.getUsers(null, curPage, pageSize);
            if (records.size() > 0) {
                list.addAll(records);
                if (records.size() == pageSize) {
                    curPage += pageSize;
                } else {
                    flag = false;
                }
            } else {
                flag = false;
            }
        }
        return list;
    }

    /**
     * 分页查询数据
     */
    public List<RecordEntity> getRecords() {
        int curPage = 0; // 起始页码
        int pageSize = 500; // 每页查询最大数
        List<RecordEntity> list = new ArrayList<>();
        boolean flag = true;
        while (flag) {
            List<RecordEntity> records = SQLManage.getRecords(curPage, pageSize);
            if (records.size() > 0) {
                list.addAll(records);
                if (records.size() == pageSize) {
                    curPage += pageSize;
                } else {
                    flag = false;
                }
            } else {
                flag = false;
            }
        }
        return list;
    }

    /**
     * 分页查询数据
     */
    public List<FileEntity> getFiles() {
        int curPage = 0; // 起始页码
        int pageSize = 500; // 每页查询最大数
        List<FileEntity> list = new ArrayList<>();
        boolean flag = true;
        while (flag) {
            List<FileEntity> records = SQLManage.getFiles(curPage, pageSize);
            if (records.size() > 0) {
                list.addAll(records);
                if (records.size() == pageSize) {
                    curPage += pageSize;
                } else {
                    flag = false;
                }
            } else {
                flag = false;
            }
        }
        return list;
    }

    /**
     * 读写授权
     */
    private boolean writeRead() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            //没有授权，编写申请权限代码
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, CommonUtils.REQUEST_CODE_WRITE);
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, CommonUtils.REQUEST_CODE_WRITE);
            return false;
        }
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.setting_backup_back:
                finish();
                break;
            case R.id.setting_backup_ll_1:
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("确认备份？").setNegativeButton("取消", null).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        // 执行数据备份
                        boolean b = writeRead();
                        if (b) {
                            try {
                                b = backUpData();
                                if (b) {
                                    ToastUtils.success(context, "备份成功", Gravity.CENTER, 0, 0);
                                } else {
                                    ToastUtils.error(context, "备份失败", Gravity.CENTER, 0, 0);
                                }
                            } catch (Exception e) {
                                Log.e(CommonUtils.TAG, "===> 【备份数据】 异常信息:" + e.getMessage());
                            }
                        }
                    }
                });
                builder.create().show();
                break;
            case R.id.setting_backup_ll_2:
                // 执行数据恢复
                boolean b = writeRead();
                if(b){
                    recoverData();
                }
                break;
        }
    }
}